package Impl

import (
	"encoding/json"
	"fmt"
	"go_code/map-collection-standalone/model/Entity"
	"io/ioutil"
	"os"
)

type CommentMapperImplByFileSystem struct {
	FilePrefix string
	FileSuffix string
}

func (this *CommentMapperImplByFileSystem) SelectById(id int64) (result Entity.Comment, err error) {
	filename := this.FilePrefix + `\` + fmt.Sprint(id) + this.FileSuffix
	_, err = os.Stat(filename)
	if os.IsNotExist(err) {
		return
	}
	jsonBytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}
	err = json.Unmarshal(jsonBytes, &result)
	return
}

func (this *CommentMapperImplByFileSystem) Update(comment Entity.Comment) (err error) {
	filename := this.FilePrefix + `\` + fmt.Sprint(comment.Id) + this.FileSuffix
	jsonBytes, err := json.Marshal(comment)
	if err != nil {
		return
	}
	err = ioutil.WriteFile(filename, jsonBytes, 0666)
	return
}

func (this *CommentMapperImplByFileSystem) DeleteById(id int64) (err error) {
	filename := this.FilePrefix + `\` + fmt.Sprint(id) + this.FileSuffix
	return os.Remove(filename)
}

func (this *CommentMapperImplByFileSystem) Insert(comment Entity.Comment) (err error) {
	filename := this.FilePrefix + `\` + fmt.Sprint(comment.Id) + this.FileSuffix
	jsonBytes, err := json.Marshal(comment)
	if err != nil {
		return
	}
	err = ioutil.WriteFile(filename, jsonBytes, 0666)
	return
}
